<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>j2ee(2) | heit0ng</title><meta name="author" content="heit0ng"><meta name="copyright" content="heit0ng"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="重定向与转发首先我们需要了解什么是重定向与转发 重定向重定向会访问服务器两次 页面先向服务器发送请求，而此时服务器会返回前端一个url，此时前端会再次用这个url访问服务器，此时才会跳转到正确页面，浏览器将会得到跳转的地址，并重新发送请求链接。在此过程中状态编码会处于302，即重定向状态，示例 123456789101112@WebServlet(&quot;&#x2F;myredirect&quot;)p">
<meta property="og:type" content="article">
<meta property="og:title" content="j2ee(2)">
<meta property="og:url" content="https://heit0ng.gitee.io/2023/03/22/j2ee(2)/index.html">
<meta property="og:site_name" content="heit0ng">
<meta property="og:description" content="重定向与转发首先我们需要了解什么是重定向与转发 重定向重定向会访问服务器两次 页面先向服务器发送请求，而此时服务器会返回前端一个url，此时前端会再次用这个url访问服务器，此时才会跳转到正确页面，浏览器将会得到跳转的地址，并重新发送请求链接。在此过程中状态编码会处于302，即重定向状态，示例 123456789101112@WebServlet(&quot;&#x2F;myredirect&quot;)p">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://s2.loli.net/2023/03/23/mTDuOeL67MFtgZs.jpg">
<meta property="article:published_time" content="2023-03-22T15:50:01.860Z">
<meta property="article:modified_time" content="2023-03-23T07:01:03.410Z">
<meta property="article:author" content="heit0ng">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://s2.loli.net/2023/03/23/mTDuOeL67MFtgZs.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://heit0ng.gitee.io/2023/03/22/j2ee(2)/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'j2ee(2)',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-03-23 15:01:03'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 5.4.0"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://s2.loli.net/2022/01/28/RkXzVpjubg3yGEI.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/archives/"><div class="headline">文章</div><div class="length-num">11</div></a></div><div class="data-item"><a href="/tags/"><div class="headline">标签</div><div class="length-num">0</div></a></div><div class="data-item"><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div></div><hr/></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://s2.loli.net/2023/03/23/mTDuOeL67MFtgZs.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">heit0ng</a></span><div id="menus"><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">j2ee(2)</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-03-22T15:50:01.860Z" title="发表于 2023-03-22 23:50:01">2023-03-22</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-03-23T07:01:03.410Z" title="更新于 2023-03-23 15:01:03">2023-03-23</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="j2ee(2)"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h3 id="重定向与转发"><a href="#重定向与转发" class="headerlink" title="重定向与转发"></a>重定向与转发</h3><p>首先我们需要了解什么是重定向与转发</p>
<h4 id="重定向"><a href="#重定向" class="headerlink" title="重定向"></a>重定向</h4><p>重定向会访问服务器两次</p>
<p>页面先向服务器发送请求，而此时服务器会返回前端一个url，此时前端会再次用这个url访问服务器，此时才会跳转到正确页面，<strong>浏览器将会得到跳转的地址，并重新发送请求链接。</strong>在此过程中状态编码会处于302，即重定向状态，示例</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">@WebServlet(&quot;/myredirect&quot;)</span><br><span class="line">public class MyRedirect extends HttpServlet &#123;</span><br><span class="line">    @Override</span><br><span class="line">    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException &#123;</span><br><span class="line">        String path = req.getContextPath();//获取你当前文件的路径</span><br><span class="line">        System.out.println(path);</span><br><span class="line">        resp.sendRedirect(path+&quot;/redirect.jsp&quot;);//重定向的位置</span><br><span class="line"></span><br><span class="line">        //不加 /就是相对路径 加了就是绝对路径</span><br><span class="line">        //resp.sendRedirect(&quot;https://www.baidu.com/&quot;);//根据重定向也可以访问到其他页面</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="转发"><a href="#转发" class="headerlink" title="转发"></a>转发</h4><p>转发只会访问服务器一次</p>
<p>前端发送请求后，会在服务器内部寻找正确的地址，相对于重定向而言再次访问的请求发出者在服务器内部，前后页面共享一个request,最后向前端呈现正确页面，实例:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">public class MyForward extends HttpServlet</span><br><span class="line">&#123;</span><br><span class="line">    @Override</span><br><span class="line">    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException &#123;</span><br><span class="line">        req.getRequestDispatcher(&quot;/forward.jsp&quot;).forward(req,resp);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>此方法浏览器不会得到转发的地址</p>
<h3 id="三个作用域"><a href="#三个作用域" class="headerlink" title="三个作用域"></a>三个作用域</h3><p>即request作用域 session作用域 application作用域</p>
<h4 id="request"><a href="#request" class="headerlink" title="request"></a>request</h4><p>通过该对象可以在一个请求中传递数据，作用范围:在一次请求中有效，即服务器跳转有效。(请求转发跳转时有效)</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">//设置域对象内容</span><br><span class="line">request.setAttribute(string name，string value);</span><br><span class="line">//获取域对象内容</span><br><span class="line">request.getAttribute(string name);</span><br><span class="line">//删除域对象内容</span><br><span class="line">request.removeAttribute(string name);</span><br></pre></td></tr></table></figure>

<p>request域对象中的数据在一次请求中有效，则经过请求转发，request域中的数据依然存在，则在请求转发的过程中可以通过request来传输/共享数据。|</p>
<p>request(作用范围为一个请求链,所有参与请求转发处理的Servlet).在两个Servlet之间通常使用请求转发来实现属性的传递与共享，request的setAttribute与getAttribute方法一般都是成对出现的，首先通过setAttribute方法设置属性与属性值，然后通过getAttribute方法根据属性获取到与该属性对应的对象值（获取到之后一般都需要进行向下类型转换，因为返回值是Object类，强转再处理后用setAttribute放回去，如果处理还未结束就转发给下一个Servlet对象处理）。setAttribute与getAttribute方法都是在服务器端内部执行的，客户端不知道服务器端是否执行过这两个方法。  </p>
<p>实例</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">@WebServlet(&quot;/servlet01&quot;)</span><br><span class="line">public class servlet01 extends HttpServlet &#123;</span><br><span class="line">    @Override</span><br><span class="line">    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException &#123;</span><br><span class="line">        String strNum = req.getParameter(&quot;number&quot;);</span><br><span class="line">        Integer number=Integer.parseInt(strNum);</span><br><span class="line">        //核心业务：开方</span><br><span class="line">        Integer result =(int)Math.sqrt(number);</span><br><span class="line">        //存入request作用域</span><br><span class="line">        req.setAttribute(&quot;number&quot;,result);</span><br><span class="line">        //插旗</span><br><span class="line">        System.out.println(&quot;开方已经完成..&quot;);</span><br><span class="line">        //发给另一个组件接着处理</span><br><span class="line">        req.getRequestDispatcher(&quot;/servlet02&quot;).forward(req,resp);</span><br><span class="line">    &#125;</span><br><span class="line">    @Override</span><br><span class="line">    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException &#123;</span><br><span class="line">        doGet(req,resp);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">@WebServlet(&quot;/servlet02&quot;)</span><br><span class="line">public class servlet02 extends HttpServlet &#123;</span><br><span class="line">    @Override</span><br><span class="line">    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException &#123;</span><br><span class="line">        //将数据get出来</span><br><span class="line">        Integer number = (Integer)req.getAttribute(&quot;number&quot;);</span><br><span class="line">        //核心业务：乘10</span><br><span class="line">        Integer result = number * 10;</span><br><span class="line">        //存入request作用域</span><br><span class="line">        req.setAttribute(&quot;number&quot;,result);</span><br><span class="line">        //插旗</span><br><span class="line">        System.out.println(&quot;乘十已经完成..&quot;);</span><br><span class="line">        //发给另一个组件接着处理</span><br><span class="line">        req.getRequestDispatcher(&quot;/servlet03&quot;).forward(req,resp);</span><br><span class="line">    &#125;</span><br><span class="line">    @Override</span><br><span class="line">    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException &#123;</span><br><span class="line">        doGet(req,resp);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">@WebServlet(&quot;/servlet03&quot;)</span><br><span class="line">public class servlet03 extends HttpServlet &#123;</span><br><span class="line">    @Override</span><br><span class="line">    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException &#123;</span><br><span class="line">        //插旗</span><br><span class="line">        System.out.println(&quot;送往显示已经完成..&quot;);</span><br><span class="line">        //发给另一个组件接着处理</span><br><span class="line">        req.getRequestDispatcher(&quot;/show.jsp&quot;).forward(req,resp);</span><br><span class="line">    &#125;</span><br><span class="line">    @Override</span><br><span class="line">    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException &#123;</span><br><span class="line">        doGet(req,resp);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>show.jsp</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">    &lt;title&gt;显示转换数据的结果&lt;/title&gt;</span><br><span class="line">&lt;/head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">&lt;h1&gt;结果&lt;/h1&gt;</span><br><span class="line">&lt;hr&gt;</span><br><span class="line">    显示转换数据的结果:&lt;%=request.getAttribute(&quot;number&quot;)%&gt;</span><br><span class="line">&lt;br&gt;</span><br><span class="line">&lt;a href=&quot;input.jsp&quot;&gt;再算一次&lt;/a&gt;</span><br><span class="line">&lt;/body&gt;</span><br><span class="line">&lt;/html&gt;</span><br></pre></td></tr></table></figure>

<h4 id="session"><a href="#session" class="headerlink" title="session"></a>session</h4><p>session的<a target="_blank" rel="noopener" href="https://so.csdn.net/so/search?q=%E4%BD%9C%E7%94%A8%E5%9F%9F&spm=1001.2101.3001.7020">作用域</a>是全局的。也就是在系统运行后，你的程序运行到session的代码时，它就一直存在</p>
<p>session用于一个会话内中的多个请求多个响应要共享数据时,在同一个浏览器窗口中，向服务器端发送多个请求访问的是那一个session对象。常用于页面保护，只有登录之后再session中设置值之后才能进行访问其他页面，也就是说，其他页面在访问之前必须要通过session进行页面的校验，每个用户只能看到自己的数据，看不到别人的数据。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">request.getSession().setAttribute() :设置属性</span><br><span class="line">request.getSession().getAttribute()：获取属性</span><br></pre></td></tr></table></figure>

<p>实例:</p>
<p>类似于一个购物车</p>
<p>购物界面:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">@WebServlet(&quot;/addservlet&quot;)</span><br><span class="line">public class addservlet extends HttpServlet&#123;</span><br><span class="line">    public void init() &#123;</span><br><span class="line">    &#125;</span><br><span class="line">    public void doGet(</span><br><span class="line">            HttpServletRequest request,</span><br><span class="line">            HttpServletResponse response)</span><br><span class="line">            throws ServletException, IOException &#123;</span><br><span class="line">        request.setCharacterEncoding(&quot;UTF-8&quot;);</span><br><span class="line">        //配置输出参数</span><br><span class="line">        response.setContentType(&quot;text/html; charset=utf-8&quot;);</span><br><span class="line">        //输出对象,即开流</span><br><span class="line">        </span><br><span class="line">        PrintWriter out = response.getWriter();</span><br><span class="line">        //创建session对象,即创建会话</span><br><span class="line">        HttpSession session = request.getSession();</span><br><span class="line">        </span><br><span class="line">        //获取参数，强转为相应的类型，更方便使用</span><br><span class="line">        String product = (String) request.getParameter(&quot;product&quot;);</span><br><span class="line">        String shopping = (String) session.getAttribute(&quot;shopping&quot;);//第一次为null</span><br><span class="line">     </span><br><span class="line">        if (shopping == null) //首次，肯定是null状态</span><br><span class="line">        &#123;</span><br><span class="line">            //设器session域的属性参数值</span><br><span class="line">            session.setAttribute(&quot;shopping&quot;, product);</span><br><span class="line">        &#125;</span><br><span class="line">        else&#123;</span><br><span class="line">            String str = shopping + &quot;&lt;br&gt;&quot; + product;</span><br><span class="line">            //str = new String(product.getBytes(), &quot;utf-8&quot;);</span><br><span class="line">            session.setAttribute(&quot;shopping&quot;, str);</span><br><span class="line">        &#125;</span><br><span class="line">        out.println(&quot;产品已添加至购物车中!&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>购物车</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">@WebServlet(&quot;/shoppingservlet&quot;)</span><br><span class="line">public class shoppingservlet extends HttpServlet &#123;</span><br><span class="line">    public void init()&#123;&#125;</span><br><span class="line">    public void doGet(</span><br><span class="line">            HttpServletRequest request,</span><br><span class="line">            HttpServletResponse response)</span><br><span class="line">                        throws ServletException, IOException&#123;</span><br><span class="line">        response.setContentType(&quot;text/html;charset=utf-8&quot;);</span><br><span class="line">        PrintWriter out = response.getWriter();</span><br><span class="line">        //获取session</span><br><span class="line">        HttpSession session=request.getSession();</span><br><span class="line">        //获取属性值</span><br><span class="line">        String shopping=(String) session.getAttribute(&quot;shopping&quot;);</span><br><span class="line"></span><br><span class="line">        if(shopping==null)&#123;</span><br><span class="line">            out.println(&quot;&lt;h1&gt;购物车为空!&lt;/h1&gt;&quot;);</span><br><span class="line">        &#125;else&#123;</span><br><span class="line">            // 设置参数的编码,避免中文乱码</span><br><span class="line">           // shopping = new String(shopping.getBytes(), &quot;utf-8&quot;);</span><br><span class="line">            out.println(&quot;&lt;h1&gt;购物车&lt;/h1&gt;&lt;br&gt;&quot;+shopping);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>产品</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html&gt;</span><br><span class="line">    &lt;head&gt;</span><br><span class="line">        &lt;meta charset=&quot;utf-8&quot;/&gt;</span><br><span class="line">        &lt;title&gt;主页面&lt;/title&gt;</span><br><span class="line">    &lt;/head&gt;</span><br><span class="line">    &lt;body&gt;</span><br><span class="line">        &lt;h1&gt;产品信息&lt;/h1&gt;</span><br><span class="line">        &lt;table width=&quot;400&quot; border=&quot;1&quot;&gt;</span><br><span class="line">    &lt;th&gt;序号&lt;/th&gt;&lt;th&gt;产品名称&lt;/th&gt;&lt;th&gt;价格(元)&lt;/th&gt;</span><br><span class="line">    &lt;tr&gt;&lt;td&gt;1&lt;/td&gt;&lt;td&gt;海信电视机&lt;/td&gt;&lt;td&gt;6999.00&lt;/td&gt;&lt;/tr&gt;</span><br><span class="line">    &lt;tr&gt;&lt;td&gt;2&lt;/td&gt;&lt;td&gt;海尔洗衣机&lt;/td&gt;&lt;td&gt;3999.00&lt;/td&gt;&lt;/tr&gt;</span><br><span class="line">    &lt;tr&gt;&lt;td&gt;3&lt;/td&gt;&lt;td&gt;格力空调&lt;/td&gt;&lt;td&gt;3269.00&lt;/td&gt;&lt;/tr&gt;</span><br><span class="line">    &lt;tr&gt;&lt;td&gt;4&lt;/td&gt;&lt;td&gt;海尔热水器&lt;/td&gt;&lt;td&gt;2780.00&lt;/td&gt;&lt;/tr&gt;</span><br><span class="line">    &lt;tr&gt;&lt;td&gt;5&lt;/td&gt;&lt;td&gt;西门子冰箱&lt;/td&gt;&lt;td&gt;2780.00&lt;/td&gt;&lt;/tr&gt;</span><br><span class="line">    &lt;/table&gt;</span><br><span class="line">    &lt;br&gt;</span><br><span class="line">    &lt;! -- 以下有两个form，请求的URL是不一样的--&gt;</span><br><span class="line">    &lt;form action=&quot;addservlet&quot; name=&quot;form1&quot;&gt;</span><br><span class="line">        输入您要购买的产品名称:&lt;br&gt;</span><br><span class="line">        &lt;input type=&quot;text&quot; name=&quot;product&quot;&gt;</span><br><span class="line">        &lt;input type=&quot;submit&quot; value=&quot;添加购物车&quot;&gt;</span><br><span class="line">    &lt;/form&gt;</span><br><span class="line">    &lt;form action=&quot;shoppingservlet&quot; name=&quot;form2&quot;&gt;</span><br><span class="line">        &lt;input type=&quot;submit&quot; value=&quot;查看购物车&quot;&gt;</span><br><span class="line">    &lt;/form&gt;</span><br><span class="line">    &lt;hr&gt;</span><br><span class="line">    思考，如何使用序号来添加购物车呢?</span><br><span class="line">    &lt;/body&gt;</span><br><span class="line">&lt;/html&gt;</span><br></pre></td></tr></table></figure>

<h4 id="application"><a href="#application" class="headerlink" title="application"></a>application</h4><p>存活范围最大的对象，只要服务器没有关闭，application对象中的数据就会一直存在。在整个服务器运行过程当中，application对象只有一个。所以Tomcat还在运行时可以打开另一个浏览器访问application的数据，常常用于项目全局信息相关，是所有用户都要能访问的数据，比如车票信息，网购的配送地址,公共聊天室</p>
<p>实例:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">@WebServlet(&quot;/adminservlet&quot;)</span><br><span class="line">public class adminservlet extends HttpServlet &#123;</span><br><span class="line">	//设置application对象</span><br><span class="line">    ServletContext sc;</span><br><span class="line">    public void init()&#123;</span><br><span class="line">        sc=this.getServletContext();//获取application对象</span><br><span class="line">    &#125;</span><br><span class="line">    public void doGet(</span><br><span class="line">            HttpServletRequest request,</span><br><span class="line">            HttpServletResponse response) throws ServletException, IOException&#123;</span><br><span class="line">        response.setContentType(&quot;text/html;charset=utf-8&quot;);</span><br><span class="line">        PrintWriter out=response.getWriter();</span><br><span class="line"></span><br><span class="line">        //获取request域中的传参</span><br><span class="line">        String newmsg=request.getParameter(&quot;msg&quot;);</span><br><span class="line">        //对日期字符串格式的处理</span><br><span class="line">        SimpleDateFormat simpleDateFormat=new SimpleDateFormat(&quot;yyyy-MM-dd:mm:ss&quot;);</span><br><span class="line">        //获取当前系统时间</span><br><span class="line">        String date=simpleDateFormat.format(new Date());</span><br><span class="line">        //获取上下文域中的参数</span><br><span class="line">        String msg=(String) sc.getAttribute(&quot;msg&quot;);</span><br><span class="line">        if(msg==null)&#123;</span><br><span class="line">            String str=&quot;发布时间&quot;</span><br><span class="line">            //注意html中的空格的表示转义</span><br><span class="line">            +&quot;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp&quot;//相当于六个汉字的宽度</span><br><span class="line">            +&quot;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp&quot;</span><br><span class="line">                    +&quot;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp&quot;+&quot;发布内容&quot;+&quot;&lt;br&gt;&quot;</span><br><span class="line">            +date+&quot;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp&quot;+newmsg;</span><br><span class="line">            sc.setAttribute(&quot;msg&quot;,str);</span><br><span class="line">        &#125;</span><br><span class="line">        else&#123;</span><br><span class="line">            String str=msg+&quot;&lt;br&gt;&quot;+date+&quot;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp&quot;+newmsg;</span><br><span class="line">            sc.setAttribute(&quot;msg&quot;,str);</span><br><span class="line">        &#125;</span><br><span class="line">        out.println(&quot;设置成功&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>页面</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=&quot;en&quot;&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">    &lt;meta charset=&quot;UTF-8&quot;&gt;</span><br><span class="line">    &lt;title&gt;系统消息管理&lt;/title&gt;</span><br><span class="line">&lt;/head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">    在这一页，多次设置系统消息，然后在另一页中，可以查看到这些消息</span><br><span class="line">    &lt;hr&gt;</span><br><span class="line">        &lt;form action=&quot;adminservlet&quot;&gt;</span><br><span class="line">            输入系统消息:</span><br><span class="line">            &lt;input type=&quot;text&quot; name=&quot;msg&quot;&gt;</span><br><span class="line">            &lt;input type=&quot;submit&quot; value=&quot;发布&quot;&gt;</span><br><span class="line">        &lt;/form&gt;</span><br><span class="line">&lt;/body&gt;</span><br><span class="line">&lt;/html&gt;</span><br></pre></td></tr></table></figure>

</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">heit0ng</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://heit0ng.gitee.io/2023/03/22/j2ee(2)/">https://heit0ng.gitee.io/2023/03/22/j2ee(2)/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://heit0ng.gitee.io" target="_blank">heit0ng</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="https://s2.loli.net/2023/03/23/mTDuOeL67MFtgZs.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="next-post pull-full"><a href="/2023/03/22/j2ee(1)/"><img class="next-cover" src="https://s2.loli.net/2023/03/22/3KqCOLtHBdvhMFe.webp" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">j2ee(1)</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://s2.loli.net/2022/01/28/RkXzVpjubg3yGEI.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">heit0ng</div><div class="author-info__description"></div></div><div class="card-info-data is-center"><div class="card-info-data-item"><a href="/archives/"><div class="headline">文章</div><div class="length-num">11</div></a></div><div class="card-info-data-item"><a href="/tags/"><div class="headline">标签</div><div class="length-num">0</div></a></div><div class="card-info-data-item"><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%87%8D%E5%AE%9A%E5%90%91%E4%B8%8E%E8%BD%AC%E5%8F%91"><span class="toc-number">1.</span> <span class="toc-text">重定向与转发</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%87%8D%E5%AE%9A%E5%90%91"><span class="toc-number">1.1.</span> <span class="toc-text">重定向</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%BD%AC%E5%8F%91"><span class="toc-number">1.2.</span> <span class="toc-text">转发</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%89%E4%B8%AA%E4%BD%9C%E7%94%A8%E5%9F%9F"><span class="toc-number">2.</span> <span class="toc-text">三个作用域</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#request"><span class="toc-number">2.1.</span> <span class="toc-text">request</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#session"><span class="toc-number">2.2.</span> <span class="toc-text">session</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#application"><span class="toc-number">2.3.</span> <span class="toc-text">application</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2023/03/22/j2ee(2)/" title="j2ee(2)"><img src="https://s2.loli.net/2023/03/23/mTDuOeL67MFtgZs.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="j2ee(2)"/></a><div class="content"><a class="title" href="/2023/03/22/j2ee(2)/" title="j2ee(2)">j2ee(2)</a><time datetime="2023-03-22T15:50:01.860Z" title="发表于 2023-03-22 23:50:01">2023-03-22</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/03/22/j2ee(1)/" title="j2ee(1)"><img src="https://s2.loli.net/2023/03/22/3KqCOLtHBdvhMFe.webp" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="j2ee(1)"/></a><div class="content"><a class="title" href="/2023/03/22/j2ee(1)/" title="j2ee(1)">j2ee(1)</a><time datetime="2023-03-22T12:20:17.683Z" title="发表于 2023-03-22 20:20:17">2023-03-22</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/05/16/C%E8%AF%AD%E8%A8%80%E5%9B%BE%E4%B9%A6%E7%AE%A1%E7%90%86%E7%B3%BB%E7%BB%9F/" title="C语言图书管理系统"><img src="https://s2.loli.net/2022/05/16/ae4E7n2D3I5mqkh.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="C语言图书管理系统"/></a><div class="content"><a class="title" href="/2022/05/16/C%E8%AF%AD%E8%A8%80%E5%9B%BE%E4%B9%A6%E7%AE%A1%E7%90%86%E7%B3%BB%E7%BB%9F/" title="C语言图书管理系统">C语言图书管理系统</a><time datetime="2022-05-16T14:28:31.730Z" title="发表于 2022-05-16 22:28:31">2022-05-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/04/07/C++qt/" title="C++Qt"><img src="https://s2.loli.net/2022/04/07/Cyg9WQLqSNxX7Av.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="C++Qt"/></a><div class="content"><a class="title" href="/2022/04/07/C++qt/" title="C++Qt">C++Qt</a><time datetime="2022-04-07T12:41:19.618Z" title="发表于 2022-04-07 20:41:19">2022-04-07</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/03/12/c++%E7%9A%84%E7%9F%A5%E8%AF%86(1)/" title="c++的知识(1)"><img src="https://s2.loli.net/2022/03/12/QrwRKYfGEmP3vVL.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="c++的知识(1)"/></a><div class="content"><a class="title" href="/2022/03/12/c++%E7%9A%84%E7%9F%A5%E8%AF%86(1)/" title="c++的知识(1)">c++的知识(1)</a><time datetime="2022-03-12T13:48:26.310Z" title="发表于 2022-03-12 21:48:26">2022-03-12</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By heit0ng</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>